//
//  SFUserAccountViewModel.swift
//  SFWeiBo
//
//  Created by 孙凡 on 16/4/11.
//  Copyright © 2016年 Edward. All rights reserved.
//

import UIKit

class SFUserAccountViewModel: NSObject {


    //判断用户是否登录
    var userLogin: Bool {

        //1.判断是否有accessToken   //2.判断是否过期
        if self.accessToken != nil && !isExpires_in{


            return true
        }

        return false
    }

    //token的值
    var accessToken: String? {

       return account?.access_token
    }
    //是否过期
    var isExpires_in: Bool{

        if NSDate().compare(account!.expiresDate!) == .OrderedAscending{

            return false
        }

        return true
    }

    //取到当前视图的模型
    var account: SFUserAccount?

    //初始化account
//    override init() {
//
//        account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? SFUserAccount
//        super.init()
//
//    }

    static let sharedAccountViewModel: SFUserAccountViewModel = {

        let vm = SFUserAccountViewModel()

        vm.account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? SFUserAccount

        return vm
    }()

    func  loadAccessToken(code code:String, callBack: ((success: Bool, error: NSError?)->())){

        // 请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"

        /**
         必选	类型及范围	说明
         client_id	true	string	申请应用时分配的AppKey。
         client_secret	true	string	申请应用时分配的AppSecret。
         grant_type	true	string	请求的类型，填写authorization_code

         grant_type为authorization_code时
         必选	类型及范围	说明
         code	true	string	调用authorize获得的code值。
         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
         */

        //拼接参数
        let paramters = [
            "client_id": SF_APPKEY,
            "client_secret": SF_APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": SF_REDIRECT
        ]

        SFNetworkTools.sharedTools.request(SFRequestMethod.POST, URLString: urlString, parameters: paramters) { (responseObjct, error) in

            if error != nil{

                callBack(success: false, error: error)

                return
            }

            //进行字典转模型,保存用户的信息
            //            print("正确........\(responseObjct)")

            /**
             "access_token" = "2.00BCAP3E7MF8dBe0122181a67nLRHD";
             "expires_in" = 157679999;  过期时间(秒)
             "remind_in" = 157679999;
             uid = 3993185765;      当前用户的ID
             */

            let dict: [String: AnyObject] = responseObjct as! [String: AnyObject]

            //            print("sssssssssssssssssss\(dict)")


            let account = SFUserAccount(dict: dict)

            //            print("sssssssssssssss\(account)sssssssssssss")

            /**
             根据
             access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
             uid            false	int64	需要查询的用户ID。
             screen_name	false	string	需要查询的用户昵称。

             获取用户信息
             */
            self.loadUserInfo(account, callBack: callBack)

        }


    }


    private func loadUserInfo(account: SFUserAccount, callBack: ((success: Bool, error: NSError?)->())){

        //请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"

        //        let urlString1 = "https://api.weibo.com/2/users/show.json?access_token=2.00BCAP3E7MF8dBe0122181a67nLRHD&uid=3993185765"

        //判断参数
        guard let accessToken = account.access_token else {
//            print("参数不够")
            callBack(success: false, error: NSError(domain: "参数不够", code: 100000, userInfo: ["accessToken":"没有参数"]))

            return
        }

        let uid = account.uid
        if uid == 0{
            callBack(success: false, error: NSError(domain: "参数不够", code: 100000, userInfo: ["uid":"没有参数"]))
            return

        }

        //请求参数
        let paramters :[String: AnyObject] = ["access_token": accessToken, "uid": uid]

        SFNetworkTools.sharedTools.request(SFRequestMethod.GET, URLString: urlString, parameters: paramters) { (responseObjct, error) in

            if error != nil {

                callBack(success: false, error: error)

                
                return
            }
            
            //请求成功后给模型赋值
            //            print(responseObjct)
            account.screen_name = responseObjct!["screen_name"] as? String
            account.avatar_large = responseObjct!["avatar_large"] as? String
            
            self.account = account
            //保存用户登录的模型,以便于下次登录(归档)
            
            NSKeyedArchiver.archiveRootObject(account, toFile: filePath)

            callBack(success: true, error: nil)
            
        }
        
        
    }


}
